package com.sjb.cp.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.sjb.cp.annotation.AuthCheck;
import com.sjb.cp.common.BaseResponse;
import com.sjb.cp.common.ResultUtils;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.manager.CosManager;
import com.sjb.cp.model.constant.UserConstant;
import com.sjb.cp.model.po.User;
import com.sjb.cp.model.request.picture.PictureUploadRequest;
import com.sjb.cp.model.vo.PictureVO;
import com.sjb.cp.service.PictureService;
import com.sjb.cp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @Author:sjb
 * @CreateTime:2025-01-17
 * @Description: 文件视图
 * @Version：1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {


    @Resource
    private CosManager cosManager;

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @PostMapping("/testUpload")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<String> testUpload(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            // 返回可访问地址
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filepath = ", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = ");
                }
            }
        }
    }


    @PostMapping("/uploadFile")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<PictureVO> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                              HttpServletRequest request, PictureUploadRequest pictureUploadRequest) {

        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    @GetMapping("/testDownLoad")
    public void testDownLoad(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectInputStream = null;
        // 处理下载到的流
        try {
            COSObject cosManagerObject = cosManager.getObject(filePath);
            objectInputStream = cosManagerObject.getObjectContent();
            byte[] byteArray = IOUtils.toByteArray(objectInputStream);

            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);

            // 写入响应
            response.getOutputStream().write(byteArray);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filePath, e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "下载失败");
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
    }


}
